package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;

import java.util.List;

@DubboService
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    // 保存语音
    @Override
    public String save(Voice voice) {
        //1、设置属性
        voice.setVid(idWorker.getNextId("voice"));
        voice.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(voice);
        //3、返回对象id
        return voice.getId().toHexString();
    }

    //获取语音
    @Override
    public Voice findRandom() {
        // 构造随机条件，sample是聚合操作提供的随机抽样方法，此处抽样1个
        Aggregation agg = Aggregation.newAggregation(Void.class, Aggregation.sample(1));
        AggregationResults<Voice> voices = mongoTemplate.aggregate(agg, Voice.class, Voice.class);
        List<Voice> list = voices.getMappedResults();
        Voice voice = voices.getUniqueMappedResult();
        return voice;
    }
}